/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package bombercloud.node;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 *
 * @author Leonardo Oliveira Moreira
 */
public class BomberCloudNode extends Thread {

    private int port;
    private ServerSocket serverSocket;

    public BomberCloudNode(int port) throws IOException {
        this.port = port;
        serverSocket = new ServerSocket(port);
    }

    @Override
    public void run() {
        if (serverSocket != null && !serverSocket.isClosed()) {
            BomberCloudNodeOutputMessage.printMessage("BomberCloudNode is running on port " + port);
        }
        while (serverSocket != null && !serverSocket.isClosed()) {
            try {
                Socket socket = serverSocket.accept();
                BomberCloudNodeThread thread = new BomberCloudNodeThread(socket);
                thread.start();
            } catch (IOException ex) {
                BomberCloudNodeOutputMessage.printErrorMessage(ex.getMessage());
            }
        }
    }

    public static void main(String[] args) {
        if (args == null || args.length != 1) {
            BomberCloudNodeOutputMessage.printErrorMessage("Invalid number of parameters");
            BomberCloudNodeOutputMessage.printMessage("Enter only the connection port");
            BomberCloudNodeOutputMessage.printMessage("Example: java -jar bombercloud-node.jar 6789");
            System.exit(-1);
        }
        int port = Integer.parseInt(args[0]);
        try {
            BomberCloudNode bomberCloudNode = new BomberCloudNode(port);
            bomberCloudNode.start();
        } catch (IOException ex) {
            BomberCloudNodeOutputMessage.printErrorMessage(ex.getMessage());
            System.exit(-1);
        }
    }
}
